<template>
  <div>
    <el-dialog v-model="dialogVisible" append-to-body title="上传文件">
      <el-upload class="upload-demo" ref="uploadRef" drag :on-exceed="handleOnExceed" 
        :auto-upload="false" :accept="props.accept"
        :limit="props.limit" 
        :http-request="httpRequest" 
        action="#" 
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖动文件到此处或者 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip justify-center flex">
            请上传{{ props.accept }}文件
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div>
          <el-button type="" @click="handleCloseUpload">取消</el-button>
          <el-button type="primary" @click="confirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { getAppEnvConfig } from '@/hooks/useEnv';
import { ElMessage, UploadInstance } from 'element-plus';
import { fileUpload } from '@/api/common/upload'
import { ref } from 'vue';

type UploadPropsType = {
  [key: string]: string
}

const props = defineProps({
  accept: '.xls,.xlsx,.jpg,.jpeg,.png,.png',
  limit: 1
})
const uploadRef = ref<UploadInstance>()
const emits = defineEmits(['uploadSuccess'])

const dialogVisible = ref(false)
const env = getAppEnvConfig()
const handleOnExceed = () => {
  ElMessage.error(`上传超过${props.limit}个文件,请先移除文件`)
}

const confirm = () => {
  uploadRef.value!.submit()
}

const httpRequest = (params: any) => {
  const { file } = params
  const formData = new FormData()
  formData.append('file', file)
  fileUpload(formData).then((result) => {
    emits('uploadSuccess',result)
    uploadRef.value!.clearFiles()
  });
}

const handleOpenUpload = () => {
  dialogVisible.value = true
}
const handleCloseUpload = () => {
  dialogVisible.value = false
}

// 导出组件或者方法
defineExpose({ handleOpenUpload, handleCloseUpload })
</script>

<style lang="scss" scoped></style>